package com.cn.lp.jpa.cq;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Collection;

public enum CQLogicalType {

    AND {
        @Override
        public <TFrom> Predicate apply(Root<TFrom> root, CriteriaQuery<?> query, CriteriaBuilder cb, Collection<Predicate> ps) {
            return cb.and(ps.toArray(new Predicate[0]));
        }

        @Override
        public Predicate combine(Predicate p1, Predicate p2, CriteriaBuilder cb) {
            return cb.and(p1, p2);
        }
    },

    OR {
        @Override
        public <TFrom> Predicate apply(Root<TFrom> root, CriteriaQuery<?> query, CriteriaBuilder cb, Collection<Predicate> ps) {
            return cb.or(ps.toArray(new Predicate[0]));
        }

        @Override
        public Predicate combine(Predicate p1, Predicate p2, CriteriaBuilder cb) {
            return cb.or(p1, p2);
        }
    },

    ;

    public abstract <TFrom> Predicate apply(Root<TFrom> root, CriteriaQuery<?> query, CriteriaBuilder cb, Collection<Predicate> ps);

    /**
     * 合并
     *
     * @param p1
     * @param p2
     * @param cb
     * @return
     */
    public abstract Predicate combine(Predicate p1, Predicate p2, CriteriaBuilder cb);

}
